package com.cndw.kungfu.model.activity.holiday;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.general.ModeExpConfig;
import com.cndw.kungfu.vo.PlayerReceiveVO;

/**
 * 万圣节变身数据保存
 * 
 * @author fantadust
 * 
 */
public class HalloweenCore {

	private static ConcurrentHashMap<Long, Integer> bsTimeMap = new ConcurrentHashMap<Long, Integer>();

	private static ConcurrentHashMap<Long, Integer> bsTypeMap = new ConcurrentHashMap<Long, Integer>();

	private static ScheduledFuture<?> task = null;

	private static int lastClac = 0;

	private static final int[] expCoef = { 0, 1, 2, 4, 8 };

	public static void bsAdd(long uid, int type) {
		bsTimeMap.put(uid, TimeProcesser.getUnixTime() + 1800);
		bsTypeMap.put(uid, type);
		if (task == null || task.isCancelled()) {
			checkTask();
		}
	}

	public static int getTBS(long uid) {
		if (bsTimeMap.containsKey(uid) && bsTypeMap.containsKey(uid) && bsTimeMap.get(uid) > TimeProcesser.getUnixTime()) {
			return bsTypeMap.get(uid);
		}
		return 0;
	}

	public static int getTBT(long uid) {
		if (bsTimeMap.containsKey(uid) && bsTimeMap.get(uid) > TimeProcesser.getUnixTime()) {
			return bsTimeMap.get(uid);
		}
		return 0;
	}

	private static synchronized void checkTask() {
		if (task != null) {
			return;
		}
		task = Context.getTimerServer().scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				runBoss();
			}

		}, 10);

	}

	private static synchronized void runBoss() {
		int currentTime = TimeProcesser.getUnixTime();
		if (lastClac + 8 >= currentTime) {
			return;
		}
		lastClac = currentTime;

		for (Map.Entry<Long, Integer> entry : bsTimeMap.entrySet()) {
			long playerId = entry.getKey();
			if (entry.getValue() < currentTime) {// 过期了.
				bsTimeMap.remove(playerId);
				bsTypeMap.remove(playerId);

			} else {

				if (!Context.getPlayerServer().isOnline(playerId)) {
					continue;
				}
				int type = bsTypeMap.get(playerId);
				Player player = Context.getPlayerServer().getByPlayerId(playerId);
				if (player == null || type == 0) {
					continue;
				}

				int expGot = ModeExpConfig.getExpOnline(player.getLevel()) * expCoef[type];
				player.alterExp(expGot);
				Context.getPlayerServer().receive(PlayerReceiveVO.RECEIVE_EXP, expGot, playerId);
				player.commitSync();
			}
		}
		if (bsTimeMap.isEmpty() && bsTypeMap.isEmpty()) {
			task.cancel(false);
			task = null;
		}

	}

}
